<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="780px" :close-on-click-modal="false"
    :before-close="handleClose">
    <div class="form">
      <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="rule-form">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="ruleForm.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>

        <el-form-item label="地址" prop="addr">
          <el-input v-model="ruleForm.addr" placeholder="请输入供应商地址" />
        </el-form-item>

        <el-form-item label="联系人" prop="liaison">
          <el-input v-model="ruleForm.liaison" placeholder="请输入联系人名称" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="评级" prop="grade">
          <el-select v-model="ruleForm.grade" filterable placeholder="请输入关键词">
            <el-option v-for="item in DictionaryList" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue + ''" />
          </el-select>
        </el-form-item>

        <el-form-item label="官网">
          <el-input v-model="ruleForm.website" placeholder="请输入官网地址" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" placeholder="请输入备注" v-model="ruleForm.remark" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>

        <el-form-item label="图片">
          <upload-image :imgUrl="ruleForm.image" @clearimgUrl="() => ruleForm.image = ''"
            @handleSuccess="handleSuccess">
          </upload-image>
        </el-form-item>

        <el-form-item label="附件">
          <!-- <el-upload ref="upload" class="upload-demo" :headers="header_url" :action="action_url" :file-list="fileList"
            :limit="1" :on-success="handlesuccess" :on-remove="handleremove" :before-upload="beforeUpload"
            list-type="text" accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx">
            <el-button icon="el-icon-upload2" size="small" type="primary">上传报告</el-button>
            <div slot="tip" class="el-upload__tip">支持xls，xlsx ,.docx , .doc，.pdf，.jpg，.png格式，大小不超过50M</div>
          </el-upload> -->
          <FileUpload v-model="ruleForm.file" :limit="1" :fileSize="50"
            :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
          </FileUpload>
        </el-form-item>
      </el-form>
      <!-- ----------------------------------------------------------------------------------------------------->
    </div>
    <div class="dialog_footer">
      <el-button type="primary" @click="handleConfirm">提交</el-button>
      <!-- <el-button  @click="handleReset">重置</el-button> -->
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { listDictionary, add, update, listDetail } from '@/api/purchasing/supplier'
import UploadImage from '@/components/upload/index.vue'
/** ------------------------------------------------------------------------------------------------------------------------------- */

/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  supplierName: "", //供应商名称
  addr: "", //地址
  liaison: "", //联系人
  phone: "", //联系电话
  grade: "0", //评级
  website: "", //官网
  image: "", //图片
  file: "", //附件
  remark: "" //备注
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */

export default {
  name: 'Form',
  components: {
    UploadImage
  },
  data () {
    return {
      dialogVisible: false,
      ruleForm: Object.assign({}, ruleForm),
      isUpdateForm: false,
      dialogTitle: '添加供应商',
      DictionaryList: [],
      fileList: [], // 上传附件的本地数组
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        supplierName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        addr: [
          { required: true, message: '请输入地址', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        liaison: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        phone: [
          // { required: true, message: '请输入联系电话', trigger: 'blur' }
          {
            required: true,
            pattern: /^((0\d{2,3}-\d{7,8})|(1[35849]\d{9}))$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur"
          }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请选择评级', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      }
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  created () {
    this.handleListType()
  },
  methods: {
    // 上传文件事件
    handlesuccess (response, file, fileList) {
      if (response.code === 200) {
        this.ruleForm.file = response.data.url
      }
      this.fileList.push({
        name: file.name,
        url: file.response
      })
    },
    // 删除上传的文件事件
    handleremove (file, fileList) {
      var _tmp = this.fileList
      for (var i = 0; i < _tmp.length; i++) {
        if (_tmp[i].name === file.name) {
          _tmp.splice(i, 1)
          break
        }
      }
      this.fileList = _tmp
    },
    // 文件上传之前的事件
    beforeUpload (val) {
      const str = val.name.substring(val.name.lastIndexOf('.') + 1)
      const isLt2M = val.size / 1024 / 1024 < 50
      if (str !== 'xls' && str !== 'xlsx ' && str !== 'docx ' && str !== 'doc' && str !== 'pdf' && str !== 'jpg' && str !== 'png') {
        this.$message({
          message: '只能上传xls，xlsx ,.docx , .doc，.pdf，.jpg，.png文件,且不超过 50M',
          type: 'warning'
        })
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 50MB!')
        return false
      }

    },

    // 类型和字典单位数据接口---------------------------------------------
    async handleListType () {
      const { data: dictionary } = await listDictionary({ dictType: 'supplier_grade', status: 0 })//字典单位
      this.DictionaryList = dictionary
    },

    // 图片上传时的处理方法-------------------------------------------
    handleSuccess (res) {
      this.ruleForm.image = res.res.data.url
    },
    // 打开表单对话框
    openDialog (id = null) {
      if (id) {
        listDetail(id).then(res => {
          this.isUpdateForm = true
          this.dialogTitle = '修改供应商'
          /** 修改时的表单参数赋值 --------------------------------------------------------------------------------------------------------------------- */
          this.ruleForm = res.data
          this.dialogVisible = true
        })
      } else {
        this.isUpdateForm = false
        this.dialogTitle = '添加供应商'
        this.dialogVisible = true
      }
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.ruleForm
          console.log('提交的表单', data)
          if (this.isUpdateForm) {
            update(data).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.resetForm('ruleForm')
              this.dialogVisible = false
              this.$emit('submit_success')
            })
          } else {
            add(data).then((res) => {
              this.$message({
                message: '创建成功',
                type: 'success'
              })
              this.fileList = []
              this.$nextTick(function () {
                this.$refs['ruleForm'].clearValidate()
              });
              this.resetForm('ruleForm')
              this.dialogVisible = false
              this.$emit('submit_success')
            })
          }
        } else {
          this.$message({
            message: '数据验证不通过，检查输入表单',
            type: 'error'
          })
          return false
        }
      })
    },
    // 重置表单
    resetForm (formName) {
      if (this.isUpdateForm) {
        this.$refs[formName].resetFields()
      } else {
        this.ruleForm = Object.assign({}, ruleForm)
        this.fileList = []
      }
      // --------consolelog('重置表单', this.ruleForm)
    },
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      this.ruleForm = Object.assign({}, ruleForm)
      this.dialogVisible = false
      this.fileList = []
      this.$nextTick(function () {
        this.$refs['ruleForm'].clearValidate()
      });
    },
    handleConfirm () {
      this.submitForm('ruleForm')
    },
    handleReset () {
      this.resetForm('ruleForm')
    }
  }
}
</script>
<style lang="scss" scoped>
.form {
  width: 410px;
  margin-left: auto;
  margin-right: auto;

  .inventory {
    display: flex;
  }
}

::v-deep .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number__increase {
  display: none;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number {
  width: 100%;
}

.dialog_footer {
  display: flex;
  justify-content: center;
}
</style>
